﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace Streambolics.App
{
    public class LogFileWriter : TriggeredComputingModule
    {
        List<GlobalLogEventArgs> _Queue = new List<GlobalLogEventArgs> ();
        private FileInfo _Path;

        public LogFileWriter (string aPath)
        {
            _Path = FileSystem.DataFile(aPath);
            GlobalLog.EventLogged += new GlobalLogEventHandler (GlobalLog_EventLogged);
        }

        void GlobalLog_EventLogged (object sender, GlobalLogEventArgs e)
        {
            _Queue.Add (e);
            Trigger ();
        }

        protected override void ExecuteTriggeredAction ()
        {
            if (_Queue.Count > 0)
            {
                try
                {
                    StringBuilder sb = new StringBuilder ();

                    foreach (var e in _Queue)
                    {
                        e.AppendTo (sb);
                    }
                    
                    _Path.AppendAllText (sb.ToString ());
                }
                finally
                {
                    _Queue.Clear ();
                }
            }
        }

        public void ShowFile ()
        {
            _Path.Edit ();
        }
    }
}
